import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import filedialog

from datetime import datetime

class App:
    def __init__(self, root):
        self.root = root
        self.init_parameters()
        self.setup_window()
        self.create_widgets()
        
    def init_parameters(self):
        # 初始化变量
        self.patterns = []                      # 存储所有形状信息
        self.dx_user = 0                        # X轴全局偏移
        self.dy_user = 0                        # Y轴全局偏移
        self.align_mark = None                  # 对齐标记的原始坐标
        self.selected_pattern = None            # 选中的形状
        self.zoom_factor = 1                    # 缩放因子
        self.canvas_size = 70000                # 画布大小
        self.init_canvas_axis = True            # 是否初始化坐标轴
        self.prev_center_x = 0                  # mark X坐标
        self.prev_center_y = 0                  # mark Y坐标
        self.is_align_mark = tk.BooleanVar()    # 是否对齐 mark
        self.temp_file_name = ""                # 临时文件名
        self.canvas_window_size = (882, 783)    # 画布窗口大小
        self.pattern_color_list = ["orange", "cyan", "gray"]
        self.pattern_status = 0                 # 0:mark, 1:unexposed pattern, 2:exposed pattern

        self.eng = 20
        self.WD_Z = 10
        self.spd = 1
        self.fov = 100
        self.resolution = 2048
        self.line_accumulation = 8
        self.beam_current = '1 nA'
        self.dose = 357
        self.time = 35.68
        # Fov(um)--Resolution--line_accumulation--beam_current(text)--dose(uC/cm2)--time(s)
        self.parameter_list = [[30,   1024, 10, '300 pA', 372, 11.2], 
                               [100,  2048, 8,  '1 nA',   357, 35.7], 
                               [120,  2048, 5,  '2 nA',   310, 22.3],
                               [160,  2048, 5,  '4 nA',   348, 22.3], 
                               [200,  2048, 9,  '3 nA',   301, 40.3], 
                               [500,  2048, 7,  '30 nA',  375, 31.4],
                               [1000, 4096, 5,  '100 nA', 892, 89.0]]
    
    def toggle_fullscreen(self, event=None):
        is_fullscreen = root.attributes("-fullscreen")
        root.attributes("-fullscreen", not is_fullscreen)
    
    def setup_window(self):
        self.root.title("EBL Drawer")
        self.root.iconphoto(True, tk.PhotoImage(file="src/icons/logo0.png"))
        self.root.geometry("1280x700")
        self.root.minsize(980, 600)
        self.root.bind("<F11>", self.toggle_fullscreen)
        self.root.bind("<Configure>", self.on_window_resize)

        # 创建菜单栏
        self.menubar = tk.Menu(self.root)
        self.root.config(menu=self.menubar)

        # 创建文件菜单
        self.file_menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="File", menu=self.file_menu)
        self.file_menu.add_command(label="Open", command=self.open_file)
        self.file_menu.add_command(label="Save", command=self.save_file)
        self.file_menu.add_separator()
        self.file_menu.add_command(label="Exit", command=self.root.quit)
        self.pattern_index = 0
    
    def create_widgets(self):
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 主框架布局(左侧)
        control_frame = ttk.Frame(main_frame, width=300)
        control_frame.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5)

        # 形状类型选择
        self.pattern_type = tk.StringVar(value="square")
        ttk.Label(control_frame, text="pattern Type:").pack(anchor=tk.W, pady=(10,0))
        ttk.Radiobutton(control_frame, text="Square", variable=self.pattern_type, 
                       value="square").pack(anchor=tk.W, padx=5)
        ttk.Radiobutton(control_frame, text="Rectangle(2:1)", variable=self.pattern_type,
                       value="rectangle").pack(anchor=tk.W, padx=5)
        
        # 参数输入框
        input_frame = ttk.LabelFrame(control_frame, text="Parameters")
        input_frame.pack(pady=5, fill=tk.X, padx=5)
        
        ttk.Label(input_frame, text="Center X (um):").grid(row=0, column=0, sticky=tk.W, padx=2, pady=2)
        self.x_entry = ttk.Entry(input_frame)
        self.x_entry.grid(row=0, column=1, padx=2, pady=2)
        
        ttk.Label(input_frame, text="Center Y (um):").grid(row=1, column=0, sticky=tk.W, padx=2, pady=2)
        self.y_entry = ttk.Entry(input_frame)
        self.y_entry.grid(row=1, column=1, padx=2, pady=2)
        
        ttk.Label(input_frame, text="Size (um):").grid(row=2, column=0, sticky=tk.W, padx=2, pady=2)
        self.size_entry = ttk.Entry(input_frame)
        self.size_entry.grid(row=2, column=1, padx=2, pady=2)
        
        # 对齐标记设置
        ttk.Checkbutton(control_frame, 
                        text="Set as Alignment Mark", 
                        variable=self.is_align_mark,
                        command=self.on_align_mark_change).pack(pady=5, anchor=tk.W, padx=5)
        
        # 添加形状按钮
        ttk.Button(control_frame, text="Add pattern", 
                  command=self.add_pattern).pack(pady=5, fill=tk.X, padx=5)
        
        # 对齐功能
        align_frame = ttk.LabelFrame(control_frame, text="Alignment")
        align_frame.pack(pady=5, fill=tk.X, padx=5)
        
        ttk.Label(align_frame, text="New X (mm):").grid(row=0, column=0, sticky=tk.W, padx=2, pady=2)
        self.new_x_entry = ttk.Entry(align_frame)
        self.new_x_entry.grid(row=0, column=1, padx=2, pady=2)
        self.new_x_entry.insert(0, 0)
        
        ttk.Label(align_frame, text="New Y (mm):").grid(row=1, column=0, sticky=tk.W, padx=2, pady=2)
        self.new_y_entry = ttk.Entry(align_frame)
        self.new_y_entry.grid(row=1, column=1, padx=2, pady=2)
        self.new_y_entry.insert(0, 0)
        
        ttk.Button(align_frame, text="Apply Alignment", 
                  command=self.apply_alignment).grid(row=2, columnspan=2, pady=5, sticky=tk.EW)
        
        # 定位按钮
        ttk.Button(control_frame, text="Locate Mark",
                   command=self.locate_mark).pack(pady=5, fill=tk.X, padx=5)
        
        # 清空画布按钮
        ttk.Button(control_frame, text="Clear Canvas",
                   command=self.clear_canvas).pack(pady=5, fill=tk.X, padx=5)
        
        # 撤销按钮
        ttk.Button(control_frame, text="Undo", 
                   command=self.undo).pack(pady=5, fill=tk.X, padx=5)

        # 创建日志显示区域
        self.log_text = scrolledtext.ScrolledText(control_frame, wrap=tk.WORD, width= 10,height=10)
        self.log_text.pack(fill=tk.BOTH, expand=True)
        self.log_text.tag_config("new", foreground="blue")
        self.log_text.tag_config("old", foreground="gray")

        # 创建EBL参数输入框
        self.setup_EBL_parameters(main_frame)

        # 创建带滚动条的Canvas
        self.setup_canvas(main_frame)
        
    def setup_canvas(self, parent):
        # 创建带滚动条的Canvas（居中布局）
        canvas_frame = ttk.Frame(parent)
        canvas_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        self.canvas = tk.Canvas(canvas_frame, bg='white', 
                               scrollregion=(-self.canvas_size, -self.canvas_size, self.canvas_size, self.canvas_size))
        
        # 设置滚动条
        h_scroll = ttk.Scrollbar(canvas_frame, orient=tk.HORIZONTAL, 
                                 command=self.scroll_handler_x)
        v_scroll = ttk.Scrollbar(canvas_frame, orient=tk.VERTICAL, 
                                 command=self.scroll_handler_y)
        self.canvas.configure(xscrollcommand=h_scroll.set, yscrollcommand=v_scroll.set)

        # 显示坐标轴
        self.draw_coordinates()
        
        # 布局管理
        self.canvas.grid(row=0, column=0, sticky="nsew")
        v_scroll.grid(row=0, column=1, sticky="ns")
        h_scroll.grid(row=1, column=0, sticky="ew")
        
        canvas_frame.grid_rowconfigure(0, weight=1)
        canvas_frame.grid_columnconfigure(0, weight=1)
        
        # 绑定事件
        self.canvas.bind("<MouseWheel>", self.zoom_handler)

        
    def user_to_canvas(self, user_x, user_y):
        """将用户坐标系转换为Canvas坐标系"""
        # 应用全局偏移和缩放
        x = (user_x + self.dx_user) * self.zoom_factor
        y = (user_y + self.dy_user) * self.zoom_factor
        # 转换为Canvas原生坐标系（原点在右上角）
        return (-x, y)
    
    def add_pattern(self):
        try:
            # 获取输入参数
            x = float(self.x_entry.get())
            y = float(self.y_entry.get())
            size = int(self.size_entry.get())
            
            # 验证尺寸
            if size <= 0:
                raise ValueError("Size must be positive")
            
            self.pattern_status = 0 if self.is_align_mark.get() else 1
            # 创建形状数据
            pattern = {
                "type": self.pattern_type.get(),
                "x": x,
                "y": y,
                "size": size,
                "pattern_index": self.pattern_index,
                "canvas_id": None,
                "pattern_status": self.pattern_status
            }

            self.pattern_index += 1

            # 如果设置为对齐标记
            if pattern["pattern_status"] == 0:
                self.align_mark = (x, y)
            
            self.patterns.append(pattern)
            self.draw_pattern(pattern)
            
        except ValueError as e:
            self.show_info(f"Invalid input: {str(e)}")
    
    def draw_pattern(self, pattern):
        # 计算形状参数
        if pattern["type"] == "square":
            half = pattern["size"] // 2
            points = [
                (-half, -half),
                (half, half)
            ]
        else:  # rectangle
            width = pattern["size"]
            height = width // 2
            points = [
                (-width//2, -height//2),
                (width//2, height//2)
            ]
        
        # 转换为Canvas坐标系
        cx, cy = self.user_to_canvas(pattern["x"], pattern["y"])
        p1 = (cx + points[0][0]*self.zoom_factor, 
              cy + points[0][1]*self.zoom_factor)
        p2 = (cx + points[1][0]*self.zoom_factor, 
              cy + points[1][1]*self.zoom_factor)
        
        # 绘制/更新形状
        if pattern["canvas_id"] is None:
            pattern_id = self.canvas.create_rectangle(
                p1[0], p1[1], p2[0], p2[1],
                outline="blue", fill=self.pattern_color_list[pattern["pattern_status"]], tags="pattern"
            )
            pattern["canvas_id"] = pattern_id
            # 绑定左键点击事件（阻止事件冒泡）
            self.canvas.tag_bind(pattern_id, "<Button-1>", 
                                lambda e, s=pattern: self.select_pattern(s) or "break")
            # 绑定右键点击事件（阻止事件冒泡）
            self.canvas.tag_bind(pattern_id, "<Button-3>", 
                                lambda e, s=pattern: self.toggle_pattern_status(s) or "break")
        else:
            self.canvas.coords(pattern["canvas_id"], p1[0], p1[1], p2[0], p2[1])
            self.canvas.itemconfig(pattern["canvas_id"], fill=self.pattern_color_list[pattern["pattern_status"]])

    def toggle_pattern_status(self, pattern):
        if pattern["pattern_status"] == 1:
            pattern["pattern_status"] = 2
            self.draw_pattern(pattern)
        elif pattern["pattern_status"] == 2:
            pattern["pattern_status"] = 1
            self.draw_pattern(pattern)
        
    def select_pattern(self, pattern):
        self.selected_pattern = pattern
        # 选中图案后修改输入框的值
        self.x_entry.delete(0, tk.END)
        self.x_entry.insert(0, int(pattern["x"]))
        self.y_entry.delete(0, tk.END)
        self.y_entry.insert(0, int(pattern["y"]))
        self.size_entry.delete(0, tk.END)
        self.size_entry.insert(0, int(pattern["size"]))

        # 修改 fov_combobox 的值并调用 on_fov_change
        self.fov_var.set(str(int(pattern["size"])))
        self.on_fov_change(None)

        # 计算实际坐标（不含缩放）
        cx = pattern["x"] + self.align_mark[0]
        cy = pattern["y"] + self.align_mark[1]
        self.show_info(f"({1e-3 * cx:.5f} mm, {1e-3 * cy:.5f} mm)")

        # 高亮选中形状
        self.canvas.itemconfig("pattern", outline="blue")
        self.canvas.itemconfig(pattern["canvas_id"], outline="red", width=2)
    
    def apply_alignment(self):
        new_x = 1e3 * float(self.new_x_entry.get())  ## 1e3: mm to um
        new_y = 1e3 * float(self.new_y_entry.get())

        self.align_mark = (new_x, new_y)
        self.show_info(f"Mark center: dx={1e-3 * self.align_mark[0]:.5f} mm, dy={1e-3 * self.align_mark[1]:.5f} mm")
    
    def redraw_all(self):
        for pattern in self.patterns:
            self.draw_pattern(pattern)
    
    def zoom_handler(self, event):
        # 处理缩放事件
        scale_factor = 0.1 if event.delta > 0 or event.num == 4 else -0.1
        self.zoom_factor += scale_factor
        self.zoom_factor = max(min(self.zoom_factor, 5), 0.1)  # 限制缩放范围
        self.zoom_factor = round(self.zoom_factor, 1)

        self.canvas.after_cancel(self._redraw_after) if hasattr(self, "_redraw_after") else None
        self.__redraw_after = self.canvas.after(50, self._do_redraw)
        current_scrollregion = self.canvas.cget("scrollregion")
        self.canvas.config(scrollregion=(
            - self.canvas_size * self.zoom_factor,
            - self.canvas_size * self.zoom_factor,
            self.canvas_size * self.zoom_factor,
            self.canvas_size * self.zoom_factor
        ))
        new_scrollregion = self.canvas.cget("scrollregion")

    def _do_redraw(self):
        self.draw_coordinates()
        self.redraw_all()
    
    def show_info(self, message):
        # 清楚旧的"new"标签
        self.log_text.tag_remove("new", "1.0", tk.END)

        # 将所有消息标记为"old"
        self.log_text.tag_add("old", "1.0", tk.END)

        # 添加新的信息
        self.log_text.insert(tk.END, message + "\n", "new")

        # 滚动到底部
        self.log_text.see(tk.END)

    def locate_mark(self):
        self.center_on_coordinate((1.0 - self.canvas_window_size[0] / self.canvas_size / 2) / 2, 
                                  (1.0 - self.canvas_window_size[1] / self.canvas_size / 2) / 2)

    def clear_canvas(self):
        self.zoom_factor = 1
        self.canvas.delete("pattern")
        self.patterns.clear()
        self.pattern_index = 0
        self.temp_file_name = ""
        self.align_mark = None
        self.show_info("Canvas cleared")

    def undo(self):
        if self.patterns:
            pattern = self.patterns.pop()
            self.canvas.delete(pattern["canvas_id"])
            self.pattern_index -= 1
            self.show_info("Undo last operation")
        else:
            self.show_info("Nothing to undo")   

    def draw_coordinates(self):
        # Clear existing elements
        self.canvas.delete("grid")
        self.canvas.delete("grid_label")
        self.canvas.delete("axis")
        
        # canvasx为实际画布的窗口坐标转换为画布坐标，1280*800的画布窗口大小为882x783
        view_left, view_top = self.canvas.canvasx(0), self.canvas.canvasy(0)
        if self.init_canvas_axis:
            view_right = view_left + (self.canvas.winfo_width() if self.canvas.winfo_width() > 1 else 882)
            view_bottom = view_top + (self.canvas.winfo_height() if self.canvas.winfo_height() > 1 else 783)
            self.init_canvas_axis = False
        else:
            view_right = view_left + self.canvas.winfo_width()
            view_bottom = view_top + self.canvas.winfo_height()

        # Calculate grid parameters
        base_step = 100
        zoom_adjusted_step = base_step / self.zoom_factor
        STEPS = [100, 200, 500, 1000, 2000, 5000, 10000]
        step = next((s for s in STEPS if zoom_adjusted_step < s), STEPS[-1])
        
        grid_spacing = step * self.zoom_factor
        
        # Draw only visible grid lines
        start_x = int(view_left // grid_spacing) - 1
        end_x = int(view_right // grid_spacing) + 1
        start_y = int(view_top // grid_spacing) - 1
        end_y = int(view_bottom // grid_spacing) + 1
        
        for i in range(start_x, end_x + 1):
            x = i * grid_spacing
            if abs(i * step) % step == 0:
                self.canvas.create_line(x, view_top, x, view_bottom, 
                                    fill="lightgray", tags="grid")
                if view_left <= x <= view_right:
                    if i == 0:
                        continue
                    self.canvas.create_text(x, 10 * (self.zoom_factor + 0.5),
                                        text=str(-i * step), tags="grid_label")
        
        for i in range(start_y, end_y + 1):
            y = i * grid_spacing
            if abs(i * step) % step == 0:
                self.canvas.create_line(view_left, y, view_right, y,
                                    fill="lightgray", tags="grid")
                if view_top <= y <= view_bottom:
                    if i == 0:
                        y += 10 * (self.zoom_factor + 0.5)
                    self.canvas.create_text(10 * (self.zoom_factor + 0.5), y,
                                        text=str(i * step), tags="grid_label")
        
        # Draw axes
        self.canvas.create_line(view_right, 0,
                            view_left, 0,
                            fill="black", arrow=tk.LAST, width=2, tags="axis")
        self.canvas.create_line(0, view_top,
                            0, view_bottom,
                            fill="black", arrow=tk.LAST, width=2, tags="axis")
        
    def scroll_handler_x(self, *args):
        # Handle horizontal scrolling
        self.canvas.xview(*args)
        # Schedule coordinate redraw after scrolling
        self.canvas.after_idle(self.draw_coordinates)

    def scroll_handler_y(self, *args):
        # Handle horizontal scrolling
        self.canvas.yview(*args)
        # Schedule coordinate redraw after scrolling
        self.canvas.after_idle(self.draw_coordinates)

    def open_file(self):
        # 打开文件
        filename = tk.filedialog.askopenfilename(
            filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
        )
        if not filename:
            return
        # 清空画布
        self.clear_canvas()
        # 逐行读取文件，加载形状
        self.show_info("File opened")
        # 读取文件
        with open(filename, "r") as f:
            for line in f:
                data = line.strip().split(",")
                pattern = {
                    "pattern_index": int(data[0]),
                    "type": data[1],
                    "x": float(data[2]),
                    "y": float(data[3]),
                    "size": int(data[4]),
                    "pattern_status": int(data[5]),
                    "canvas_id": None
                }
                if pattern['pattern_status'] == 0:
                    self.align_mark = (0, 0)
                self.patterns.append(pattern)
                self.pattern_index = pattern['pattern_index'] + 1
                # 输出self.patterns中的所有形状数据
                self.draw_pattern(pattern)
        

    def save_file(self):
        self.save_pattern_to_file()
    
    def on_align_mark_change(self):
        if self.is_align_mark.get():
            self.show_info("Set as alignment mark")
            # 将输入框的值设置为0
            self.x_entry.delete(0, tk.END)
            self.x_entry.insert(0, self.prev_center_x)
            self.y_entry.delete(0, tk.END)
            self.y_entry.insert(0, self.prev_center_y)
            # 将两个输入框设置为无法修改
            self.x_entry.configure(state="disabled")
            self.y_entry.configure(state="disabled")
        else:
            self.show_info("Unset as alignment mark")
            self.x_entry.configure(state="enabled")
            self.y_entry.configure(state="enabled")

    def format_pattern_data(self, pattern):            
        return f"{pattern['pattern_index']},{pattern['type']},{pattern['x']},{pattern['y']},{pattern['size']},{pattern['pattern_status']},{pattern['canvas_id']}\n"
    
    def save_pattern_to_file(self):
        try:
            # 保存到临时文件
            if self.temp_file_name == "":
                now = datetime.now().strftime("%Y%m%d%H%M%S")
                self.temp_file_name = f"ebldrawer_temp_{now}.txt"
            with open(self.temp_file_name, "a") as f:
                for pattern in self.patterns:
                    f.write(self.format_pattern_data(pattern))
        except Exception as e:
            self.show_info(f"Error saving pattern: {str(e)}")

    def center_on_coordinate(self, x, y):
        try:
            self.canvas.xview_moveto(x)
            self.canvas.yview_moveto(y)

        except Exception as e:
            self.show_info(f"Error centering on coordinates: {str(e)}")

        self.draw_coordinates()

    def on_window_resize(self, event):
        if hasattr(self, "canvas"):
            self.draw_coordinates()

    def setup_EBL_parameters(self, parent):
        # 创建带滚动条的Canvas（居中布局）
        ebl_frame = ttk.Frame(parent)
        ebl_frame.pack(side=tk.RIGHT, fill=tk.Y, padx=5, pady=5)

        # 创建EBL参数输入框
        ebl_input_frame = ttk.LabelFrame(ebl_frame, text="EBL Parameters")
        ebl_input_frame.pack(pady=5, fill=tk.X, padx=5)

        # Eng 输入框
        ttk.Label(ebl_input_frame, text="Eng (keV):").grid(row=0, column=0, sticky=tk.W, padx=2, pady=2)
        self.eng_entry = ttk.Entry(ebl_input_frame, width=20)
        self.eng_entry.grid(row=0, column=1, padx=2, pady=2)
        self.eng_entry.delete(0, tk.END)
        self.eng_entry.insert(0, self.eng)
        self.eng_entry.configure(state="disabled")

        # WD&Z 输入框
        ttk.Label(ebl_input_frame, text="WD&Z (mm):").grid(row=1, column=0, sticky=tk.W, padx=2, pady=2)
        self.work_dist_entry = ttk.Entry(ebl_input_frame, width=20)
        self.work_dist_entry.grid(row=1, column=1, padx=2, pady=2)
        self.work_dist_entry.delete(0, tk.END)
        self.work_dist_entry.insert(0, self.WD_Z)
        self.work_dist_entry.configure(state="disabled")

        # spd 输入框
        ttk.Label(ebl_input_frame, text="Spd (us/pxl):").grid(row=2, column=0, sticky=tk.W, padx=2, pady=2)
        self.spd_entry = ttk.Entry(ebl_input_frame, width=20)
        self.spd_entry.grid(row=2, column=1, padx=2, pady=2)
        self.spd_entry.delete(0, tk.END)
        self.spd_entry.insert(0, self.spd)
        self.spd_entry.configure(state="disabled")

        # Fov 下拉框
        ttk.Label(ebl_input_frame, text="Fov (um):").grid(row=3, column=0, sticky=tk.W, padx=2, pady=2)
        self.fov_var = tk.StringVar()
        self.fov_var.set(str(self.fov))
        fov_combobox = ttk.Combobox(ebl_input_frame, textvariable=self.fov_var, width=17)
        # values取self.parameter_list中的第一列
        fov_combobox["values"] = [str(p[0]) for p in self.parameter_list]
        fov_combobox.grid(row=3, column=1, padx=2, pady=2)
        fov_combobox.bind("<<ComboboxSelected>>", self.on_fov_change)

        # Resolution 下拉框
        ttk.Label(ebl_input_frame, text="Resolution (pxl):").grid(row=4, column=0, sticky=tk.W, padx=2, pady=2)
        self.resolution_var = tk.StringVar()
        self.resolution_var.set(str(self.resolution))
        resolution_combobox = ttk.Combobox(ebl_input_frame, textvariable=self.resolution_var, width=17, state="disabled")
        resolution_combobox["values"] = [1024, 2048, 4096]
        resolution_combobox.grid(row=4, column=1, padx=2, pady=2)
        resolution_combobox.bind("<<ComboboxSelected>>", self.on_resolution_change)

        # line_accumulation 输出框
        ttk.Label(ebl_input_frame, text="Line Accumulation:").grid(row=5, column=0, sticky=tk.W, padx=2, pady=2)
        self.line_accumulation_entry = ttk.Entry(ebl_input_frame, width=20)
        self.line_accumulation_entry.grid(row=5, column=1, padx=2, pady=2)
        self.line_accumulation_entry.delete(0, tk.END)
        self.line_accumulation_entry.insert(0, self.line_accumulation)
        self.line_accumulation_entry.configure(state="disabled")

        # beam_current 下拉框
        ttk.Label(ebl_input_frame, text="Beam Current:").grid(row=6, column=0, sticky=tk.W, padx=2, pady=2)
        self.beam_current_var = tk.StringVar()
        self.beam_current_var.set(self.beam_current)
        beam_current_combobox = ttk.Combobox(ebl_input_frame, textvariable=self.beam_current_var, width=17, state="disabled")
        beam_current_combobox["values"] = ["300 pA", "1 nA", "2 nA", "3 nA", "4 nA", "30 nA", "100 nA"]
        beam_current_combobox.grid(row=6, column=1, padx=2, pady=2)
        beam_current_combobox.bind("<<ComboboxSelected>>", self.on_beam_current_change)

        # time 输入框
        ttk.Label(ebl_input_frame, text="Time (s):").grid(row=7, column=0, sticky=tk.W, padx=2, pady=2)
        self.time_entry = ttk.Entry(ebl_input_frame, width=20)
        self.time_entry.grid(row=7, column=1, padx=2, pady=2)
        self.time_entry.delete(0, tk.END)
        self.time_entry.insert(0, self.time)
        self.time_entry.configure(state="disabled")

        # dose 输入框
        ttk.Label(ebl_input_frame, text="Dose (uC/cm2):").grid(row=8, column=0, sticky=tk.W, padx=2, pady=2)
        self.dose_entry = ttk.Entry(ebl_input_frame, width=20)
        self.dose_entry.grid(row=8, column=1, padx=2, pady=2)
        self.dose_entry.delete(0, tk.END)
        self.dose_entry.insert(0, self.dose)
        self.dose_entry.configure(state="disabled")
        
        

    def on_fov_change(self, event):
        selected_fov = int(self.fov_var.get())
        for params in self.parameter_list:
            if params[0] == selected_fov:
                self.resolution_var.set(str(params[1]))

                self.line_accumulation_entry.configure(state="normal")
                self.line_accumulation_entry.delete(0, tk.END)
                self.line_accumulation_entry.insert(0, params[2])
                self.line_accumulation_entry.configure(state="disabled")

                self.beam_current_var.set(params[3])

                self.dose_entry.configure(state="normal")
                self.dose_entry.delete(0, tk.END)
                self.dose_entry.insert(0, params[4])
                self.dose_entry.configure(state="disabled")

                self.time_entry.configure(state="normal")
                self.time_entry.delete(0, tk.END)
                self.time_entry.insert(0, params[5])
                self.time_entry.configure(state="disabled")
                break

    def on_resolution_change(self, event):
        pass

    def on_beam_current_change(self, event):
        pass

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

